package com.sikulifang.frequency.service.impl;

import com.sikulifang.frequency.service.IFrequency;
import com.sikulifang.frequency.utils.FrequencyUtil;
import lombok.Data;

import java.util.concurrent.Semaphore;

import static com.sikulifang.frequency.utils.FrequencyUtil.rest;

/**
 * 单类型线程控制
 *
 * @author zhoul 2020-11-20
 * @since 3.0.0
 */
@Data
public class SingleTypeFrequency implements IFrequency {

    /**
     * true - 固定延迟时长
     * false - 动态延迟时长
     */
    private boolean interfaceInterval;

    /**
     * 接口延迟时间
     */
    private Long interfaceDelayTime;
    /**
     * 接口延迟时间
     */
    private Long interfaceWaitingTime;

    /**
     * true - 开启延迟时长
     * false - 关闭延迟时长
     */
    private boolean interval;

    /**
     * 间隔时长(ms)
     */
    private Long intervalTime;

    private final Semaphore semaphore = new Semaphore(1, true);

    @Override
    public void acquire(String type) throws InterruptedException {
        FrequencyUtil.acquire(semaphore, interfaceWaitingTime);
    }

    @Override
    public void delay(String type, long time) {
        if (interfaceInterval) {
            rest(interfaceDelayTime);
        } else {
            if (time >= 0 && time < interfaceDelayTime) {
                rest(interfaceDelayTime - time);
            }
        }
    }

    @Override
    public void release(String type) {
        if (semaphore.availablePermits() == 0) {
            semaphore.release();
        }
    }
}
